﻿using Colorful.Caching;
using Colorful.Furniture.Extensions;
using Colorful.Furniture.SysManagement;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using Volo.Abp.Application.Services;

namespace Colorful.Furniture.PermissionManagement;

/// <summary>
///  初始化数据
/// </summary>
public class InitDataAppService : ApplicationService
{
    private readonly IFreeSql _freeSql;
    private readonly ILogger<InitDataAppService> _logger;
    private readonly IRedisCache _cache;
    private const string RedisKey = "SyncDataSchema";

    /// <summary>
    /// 初始化数据
    /// </summary>
    public InitDataAppService(IFreeSql freeSql,
        ILogger<InitDataAppService> logger,
        IRedisCache cache)
    {
        _freeSql = freeSql;
        _logger = logger;
        _cache = cache;
    }

#if DEBUG

    /// <summary>
    ///  初始化数据
    /// </summary>
    public bool Initialization()
    {
        var isSync = _cache.Get<string>(RedisKey);
        if (isSync == "1")
        {
            _logger.LogInformation("数据库表结构和数据已完成同步");

            return true;
        }

        _logger.LogInformation("开始同步数据库表结构和数据");

        //同步权限相关的数据表结构
        _freeSql.CodeFirst.SyncStructure<SysApi>();

        _freeSql.CodeFirst.SyncStructure<SysDictionary>();

        _freeSql.CodeFirst.SyncStructure<SysApiLog>();

        _freeSql.CodeFirst.SyncStructure<SysManager>();

        _freeSql.CodeFirst.SyncStructure<SysManagerIdentity>();

        _freeSql.CodeFirst.SyncStructure<SysManagerLog>();

        _freeSql.CodeFirst.SyncStructure<SysPermission>();

        _freeSql.CodeFirst.SyncStructure<SysPermissionApi>();

        _freeSql.CodeFirst.SyncStructure<SysResource>();

        _freeSql.CodeFirst.SyncStructure<SysRole>();

        _freeSql.CodeFirst.SyncStructure<SysRoleAccess>();

        //检查系统管理员表中是否有超级管理员权限用户存在
        var sysManager = _freeSql.Select<SysManager>()
            .Where(x => x.IsSupper)
            .ToOne();

        //不存则创建
        if (sysManager != null)
        {
            _cache.Set("RedisKey", "1");

            return true;
        }

        //新增管理员主表
        _freeSql.Transaction(() =>
        {
            sysManager = new SysManager
            {
                Id = Guid.NewGuid(),
                AddTime = DateTime.Now,
                Age = 30,
                Name = "超级管理员",
                Avatar = "https://lyoss.ammcloud.cn/uploadFile/avatar8.jpg",
                Email = "bf1234@qq.com",
                ManagerType = 1,
                Phone = "18888888888",
                Sex = "男",
                Position = "超级管理员",
                IsSupper = true,
                UserName = "admin",
                Birthday = DateTime.Parse("1991-07-05"),
                IsDeleted = false,
                IsDisabled = false
            };

            var resultSysManager = _freeSql.Insert(sysManager).ExecuteAffrows();

            //管理员认证数据
            var sysManagerIdentity = new SysManagerIdentity
            {
                Id = new Guid(),
                ManagerId = sysManager.Id,
                IdentityType = "Password",
                Identifier = "admin",
                Credential = "123@qwe".Encrypt32()
            };

            var resultIdentity = _freeSql.Insert(sysManagerIdentity).ExecuteAffrows();

            _logger.LogInformation($"新增超级管理员数据 {resultSysManager} 条，新增管理员认证 {resultIdentity} 条");

            //写入数据字典
            var dataDictionaryList = new List<SysDictionary>
                {
                    new SysDictionary {Code = "ResourceOperation",Id = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Title = "资源操作代码",Value = "",IsDeleted = false,Sort = 1},
                    new SysDictionary { Code = "Show",Title = "显示",Remark = "定义菜单是否展示",Value = "el-icon-open",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 1,IsDeleted = false},
                    new SysDictionary { Code = "Add",Title = "添加",Value = "el-icon-circle-plus-outline",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort =2,IsDeleted = false},
                    new SysDictionary { Code = "Search",Title = "查询",Value = "el-icon-search",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 3,IsDeleted = false},
                    new SysDictionary { Code = "Delete",Title = "删除",Value = "el-icon-delete-solid",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 4,IsDeleted = false},
                    new SysDictionary { Code = "Audit",Title = "审核",Value = "el-icon-s-claim",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 5,IsDeleted = false},
                    new SysDictionary { Code = "View",Title = "查看",Remark = "定义详情、基本信息等等",Value = "el-icon-view",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 1,IsDeleted = false},
                    new SysDictionary { Code = "Export",Title = "导出",Value = "el-icon-folder-opened",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 6,IsDeleted = false},
                    new SysDictionary { Code = "Import",Title = "导入",Value = "el-icon-folder",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 7,IsDeleted = false},
                    new SysDictionary { Code = "Edit",Title = "编辑",Value = "el-icon-edit",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 8,IsDeleted = false},
                    new SysDictionary { Code = "Submit",Title = "提交",Value = "el-icon-edit-outline",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 9,IsDeleted = false},
                    new SysDictionary { Code = "Set",Title = "设置",Remark = "定义密码设置、设置状态等",Value = "el-icon-c-scale-to-original",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 10,IsDeleted = false},
                    new SysDictionary { Code = "Save",Title = "保存",Value = "el-icon-circle-check",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 11,IsDeleted = false},
                    new SysDictionary { Code = "Sync",Title = "同步",Value = "el-icon-upload2",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 12,IsDeleted = false},
                    new SysDictionary { Code = "Refresh",Title = "刷新",Value = "el-icon-refresh",Id = Guid.NewGuid(),ParentId = Guid.Parse("091deae6-1981-4d6a-9e29-c7a6175c4fd8"),Sort = 13,IsDeleted = false}
                };

            var dictionaryResult = _freeSql.Insert(dataDictionaryList).ExecuteAffrows();

            _logger.LogInformation($"新增数据字典数据 {dictionaryResult} 条");

            _cache.Set(RedisKey, "1");
        });

        return true;
    }

#endif
}